<!--API资产划转-->
<template>
  <div class="bg bg1">
    <template v-if="api">
      
      <!--币-->
      <div class="coin bg2" @click="coinClick">
        <text class="font28 text2 width110">{{T('币种')}}</text>
        <text class="font30 text1">{{coin}}</text>
        <div class="all"></div>
        <LImage class="arrow-right-img" :src="Config.img('jiantou_hui.png')"></LImage>
      </div>

      <!--账户-->
      <div class="account bg2">

        <div class="acenter">
          <text class="font28 text2">{{T('从')}}</text>
          <div class="height8"></div>
          <LImage class="dian-img" :src="Config.img('zc_huazhuan1.png')"></LImage>
          <div class="height8"></div>
          <text class="font28 text2">{{T('到')}}</text>
        </div>

        <div>
          <div class="tap">
            <text class="font30 text1">{{T(accountA)}}</text>
          </div>

          <div class="line line1"></div>

          <div class="tap">
            <text class="font30 text1">{{T(accountB)}}</text>
          </div>
        </div>

        <LImage class="rotate-img" ref="rotate" :src="Config.img('zc_huazhuan.png')" @click="rotateClick"></LImage>
      </div>
      
      <!--交易对-->
      <div class="coin bg2" 
      v-if="
      usdtAccount && !isUsdt" 
      @click="pairClick">
        <text class="font28 text2">{{T('交易对')+'  '}}</text>
        <text class="font30 text1">{{pairMap ? (pairMap.counterCoin+' '+T('永续')+'/'+pairMap.baseCoin) : T('请选择交易对')}}</text>
        <div class="all"></div>
        <LImage class="arrow-right-img"  :src="Config.img('jiantou_hui.png')" @click="varyClick"></LImage>
      </div>

      <!--数量-->
      <div class="input bg2">
        <text class="font28 text2 width110">{{T('数量')}}</text>
        <input class="input-content font28 text1" ref="input" v-model="num" type="number" @input="onInput" @focus="onFocus" @blur="onBlur">
        <text class="font28 text3">{{'  ' + coin}}</text>
        <div class="input-line line1"></div>
        <div class="input-all" @click="allClick">
          <text class="font24 main-t1">{{T('全部')}}</text>
        </div>
      </div>

      <div class="height20"></div>
      <div class="row">
        <div class="width40"></div>
        <text class="font24 text3">{{T('可用') + ' ' + available + ' ' + coin}}</text>
      </div>
      
      <!--按钮-->
      <div class="but main-bt1" @click="okClick">
        <text class="font30 text1">{{T('确认')}}</text>
      </div>
    </template>
  </div>
</template>

<style src="@/_css/style.css" ></style>
<style scoped>
.bg {
  flex: 1;
  padding-left: 20px;
  padding-right: 20px;
}

/*********************************** 币*/
.coin {
  flex-direction: row;
  align-items: center;

  height: 98px;
  border-radius: 24px;

  padding-left: 40px;
  padding-right: 60px;

  margin-top: 30px;
}
.arrow-right-img {
  width: 13px;
  height: 20px;
}

/*********************************** 账户*/
.account {
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  border-radius: 24px;

  padding-left: 40px;
  padding-right: 40px;

  margin-top: 40px;
}
.tap {
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  width: 400px;
  height: 110px;
}
.line {
  width: 400px;
  height: 1px;
}
.arrow-down-img {
  width: 17px;
  height: 21px;
}
.rotate-img {
  width: 60px;
  height: 60px;
}
.dian-img {
  width: 19px;
  height: 23px;

  margin-top: 14px;
  margin-bottom: 14px;
}

/*********************************** 币*/
.input{
  flex-direction: row;
  align-items: center;
  height: 98px;
  border-radius: 24px;
  padding-left: 40px;

  margin-top: 40px;
}
.input-content {
  height: 88px;
  flex: 1;
  text-align: right;
}
.input-line{
  width: 2px;
  height: 24px;

  margin-left: 20px;
}
.input-all {
  flex-direction: row;
  justify-content: center;
  align-items: center;
  height: 88px;
  padding-left: 20px;
  padding-right: 20px;
  margin-right: 20px;
}

/*********************************** 按钮*/
.but{
  justify-content: center;
  align-items: center;
  height: 80px;
  border-radius: 12px;

  margin-top: 80px;
}

/*********************************** 间距*/
.width110{
  width: 110px;
}
.height8 {
  height: 8px;
}
</style>

<script>

import jnavigator from "@/_js/navigator";
import jhttps from "@/_js/https";
import jconfig from "@/_js/config";
import jmath from "@/_js/math";
import jmodal from "@/_js/modal";
import japi from "@/_js/api";
import jbroadcast from "@/_js/broadcast"; 
import janimation from "@/_js/animation"; 

const weexFunction = weex.requireModule("WeexFunction");
const globalEvent = weex.requireModule('globalEvent');

import I18N from "@/_i18n/i18n";
var T = I18N.t;
weexFunction.setTitle(T('资产划转'));

export default {
  
  data() {
    return {
      T:T,
      Config:jconfig,

      accounts:[],
      accountA:'币币账户',
      accountB:'',
      accountType:{'币币账户':'spot', '币本位合约账户':'swap', 'USDT合约账户':'linear-swap'},

      usdtAccount:true, //true U本位合约账户参与划转
      
      apiId:undefined,
      api:undefined,
      coins:[],

      coin:'', //币
      available:'0', //可划转数量
      num:'', //划转数量

      pairMap:undefined,
    };
  },

  computed: {
    
    //true U本位，不用选交易对
    isUsdt() {
      
      weexFunction.debugLog(japi.isExchangeUSDT(this.api.exchangeName));

      try {
        return japi.isExchangeUSDT(this.api.exchangeName);
      } catch (error) {
        return false;
      }
    }
  },

  created() {
    
    var param = weex.config;
    this.apiId = param.apiId;
    this.pairMap = param.pairMap;


    jconfig.init(()=>{
      this.initData();
    }, [jconfig.OPT_CURRENT_BZ]);

    //Api更新通知
    globalEvent.addEventListener("apiUp",(e)=>{
      japi.getApi(this.apiId, 'all', (api)=>{
        this.initCoins(api);
        this.initAvailable();
        this.api = api;
      });
    });
  },



  methods: {

    initData() {
      
      japi.getApi(this.apiId, 'all', (api)=>{


        this.initAccounts(api);
        this.isUsdtAccount();
        this.initCoins(api);
        this.initCoin();
        this.initAvailable();
        this.api = api;
      });
    },

    //初始化账户
    initAccounts(api) {

      this.accounts = ['币币账户'];
      api.linerSwapAssets && this.accounts.push('USDT合约账户');
      api.swapAssets && this.accounts.push('币本位合约账户');

      if(this.accounts.length <= 1){
        jmodal.alert(T('未开通合约交易功能，无法划转资产'),()=>{
            jnavigator.back();
        });
        return;
      }
      this.accountB = this.accounts[1];
    },

    //USDT合约账户判断
    isUsdtAccount() {
      this.usdtAccount = (this.accountA == 'USDT合约账户' || this.accountB == 'USDT合约账户');
      this.pairMap = this.usdtAccount ? this.pairMap : null;
    },
    
    //初始化资产（币）数组
    initCoins(api){

      var coins;
      if (this.accountA == '币币账户') {
        coins = api.accountAssets;
      } else if (this.accountA == '币本位合约账户') {
        coins = api.swapAssets;
      } else if (this.accountA == 'USDT合约账户') {
        coins = api.linerSwapAssets;
      } 

      //计算可划转数量
      for (let index = 0; index < coins.length; index++) {
        var coinBean = coins[index];
        var coin = this.accountA == 'USDT合约账户' ? 'USDT' : coinBean.currency;
        var withdrawAvailable = this.accountA == '币币账户' ? coinBean.availableReal : coinBean.withdrawAvailable;
        withdrawAvailable = Number(withdrawAvailable) < 0 ? '0' : withdrawAvailable;
        coinBean.withdrawAvailable = jmath.gfCoin(withdrawAvailable, coin, 2);
      }
      this.coins = coins;
    },

    //初始化划转币种
    initCoin() {

      if (this.usdtAccount) {
        this.coin = 'USDT';
        return;
      }
      this.coin = this.coin.length ? this.coin : this.coins[0].currency;
    },
    
    //初始化可用余额
    initAvailable() {
      
      //获取余额
      var getAvailable = (coin) =>{
        for (let index = 0; index < this.coins.length; index++) {
          var coinBean = this.coins[index];
          if (coinBean.currency == coin) {
           return coinBean.withdrawAvailable;
          }
        }
        return '0';
      };
      
      if (this.accountA == 'USDT合约账户') {

        if (this.isUsdt) {
          this.available = getAvailable('USDT');
        } else {
          this.available = this.pairMap ? getAvailable(this.pairMap.counterCoin) : '0';
        }
      } else {
        this.available = getAvailable(this.coin);
      }
    },

    /********************************** HTTP*/
    //http获取服务器公钥
    httpGetPublicKey(){
      
      jmodal.showLoad();
      var param = {'serverType':'accountServer'};
      jhttps.post("assetsV2/getPublicKey",param,true,(data)=>{

        if(data.status == 200){
          data = data.data;
          var key =  data['publicKey'];
          japi.rsaApi(this.api, key, (rsa)=>{
            this.httpAccountTransfer(rsa);
          });

        } else {
          jmodal.hideLoad();
          jmodal.toast(data.msg);
        }
      });
    },

    //http资产划转
    httpAccountTransfer(apiData){
      
      var contractId = this.pairMap ? this.pairMap.contractId : '';
      
      var paramStr = {'from':this.accountType[this.accountA],
                      'to':this.accountType[this.accountB],
                      'currency':this.coin,
                      'amount':this.num};
      if (contractId.length) {
        paramStr['margin-account'] = contractId;
      }

      paramStr = JSON.stringify(paramStr);
      var param = {'apiData':apiData, 'param':paramStr};
      jhttps.postX("assetsV2/accountTransfer",param,true,(data)=>{

        if(data.status == 200){
          
          //同步完成
          var ok = ()=>{
            setTimeout(() => {
              this.num = '';
              jmodal.hideLoad();
              jmodal.toast(T('划转成功'));
              jnavigator.back();
            }, 3000);
          };

          //同步指定合约币种资产----同步API因为交易所限制，无法频繁同步合约资产。
          japi.synchroCoinContract(this.apiId, 
                                  contractId, 
                                  'contract_usdt');
          japi.synchroApi(this.apiId, ok, ok);
        }  else if (data.status == 6074) {

          jmodal.hideLoad();
          jmodal.alert({'message':'API资产已改变，同步资产后重新尝试划转', 'btn':'同步资产'}, ()=>{

            jmodal.showLoad();
            japi.synchroApi(this.apiId, ()=>{
              setTimeout(() => {
                jmodal.hideLoad();
              }, 3000);
            }, ()=>{
              jmodal.hideLoad();
              jmodal.toast(T('同步失败'));
            });
          })
        } else {
          jmodal.hideLoad();
          jmodal.toast(data.msg);
        }
      });
    },

    /********************************** 输入框监听*/
    //键盘隐藏
    onBlur(){
      this.num = jmath.toString(this.num);
    },

    /********************************** 点击触发*/
    //账户A
    account1(){
      if (this.accountA == '币币账户'){
        return;
      }

      var accounts = [];
      for (let index = 0; index < this.accounts.length; index++) {
        var str = this.accounts[index];
        accounts.push(T(str));
      }

      jmodal.actionSheet(accounts, T(this.accountA), (value)=>{
        
        for (let index = 0; index < accounts.length; index++) {
          var str = accounts[index];
          if (str == value) {
            value = this.accounts[index];
            break;
          }
        }

        if (this.accountA == value) {
          return;
        }

        if (this.accountB == value) {
          this.accountB = this.accountA;
          this.accountA = value;
        } else {
          this.accountA = value;
        }

        if (value != '币币账户' && this.accountB != '币币账户') {
          this.accountB = '币币账户';
        }

        this.coin = '';
        this.num = '';
        this.isUsdtAccount();
        this.initCoins(this.api);
        this.initCoin();
        this.initAvailable();
      });
    },

    //账户2
    account2(){
      if (this.accountB == '币币账户'){
        return;
      }


      var accounts = [];
      for (let index = 0; index < this.accounts.length; index++) {
        var str = this.accounts[index];
        accounts.push(T(str));
      }

      jmodal.actionSheet(accounts, T(this.accountB), (value)=>{
        
        for (let index = 0; index < accounts.length; index++) {
          var str = accounts[index];
          if (str == value) {
            value = this.accounts[index];
            break;
          }
        }
        
        if (this.accountB == value) {
          return;
        }
        
        if (this.accountA == value) {
          this.accountA = this.accountB;
          this.accountB = value;
        } else {
          this.accountB = value;
        }
        
        if (value != '币币账户' && this.accountA != '币币账户') {
          this.accountA = '币币账户';
        }

        this.coin = '';
        this.num = '';
        this.isUsdtAccount();
        this.initCoins(this.api);
        this.initCoin();
        this.initAvailable();
      });
    },

    //旋转
    rotateClick() {

      janimation.start('api_transfer', this.$refs.rotate, 250, 180, 1);
      
      var accountB = this.accountA
      this.accountA = this.accountB;
      this.accountB = accountB;

      this.coin = '';
      this.num = '';
      this.initCoins(this.api);
      this.initCoin();
      this.initAvailable();
    },

    //币点击
    coinClick() {
      // if (this.usdtAccount) {
      //   return;
      // }

      var param = {'coins':this.coins, 'coin':this.coin};
      var nav = {'navColor':'#0c0c0c'};
      jnavigator.open('', 'home/SelectCoin', param, nav);

      jbroadcast.subscribeOnce('SelectCoin', (coin)=>{
        this.coin = coin;
        this.num = '';
        this.initAvailable();
      })
    },

    //交易对点击
    pairClick() {
      
      var param = {exchangeId:this.api.exchangeId,
                  counterCoin:this.pairMap ? this.pairMap.counterCoin : '',
                  baseCoin:this.pairMap ? this.pairMap.baseCoin : ''};
      jnavigator.open('', 'upContract/CSelectPair', param);

      jbroadcast.subscribeOnce('CSelectPair', (pairMap)=>{
        this.pairMap = pairMap;
        this.initAvailable();
      });
    },

    //全部
    allClick() {
      this.num = this.available;
    },

    //确认
    okClick() {
      this.$refs.input.blur();
      
      if (this.usdtAccount && !this.pairMap && !this.isUsdt) {
        jmodal.toast(T('请选择交易对'));
      } else if (this.num.length <= 0) {
        jmodal.toast(T('请输入划转数量'));
      } else if (Number(this.num) == 0) {
        jmodal.toast(T('划转数量不合法'));
      } else if (Number(this.num) > Number(this.available)) {
        jmodal.toast(T('可用余额不足'));
      } else {
        this.httpGetPublicKey();
      }
    }
  },
};

</script>
